using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Android.App;
using Android.Content;
using Android.GoogleMaps;
using Android.Locations;
using Android.OS;
using Android.Preferences;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using NorthStar.Passenger.Application;

using NorthStar.Passenger.Application.Responses;
using RestSharp;
using TheNorthStar.Api.Requests;
using TheNorthStar.Api.Results;
using Object = Java.Lang.Object;

namespace NorthStar.Passenger
{
	public class Location
	{
		public double lat{get;set;}
		public double lng{get;set;}
	}
	
	public class AddressComponents
	{
		public string long_name{get;set;}
		public string short_name{get;set;}
		public string[] types{get;set;}
	}
	
	public class Geometry{
		public Location location{get;set;}
		public string location_type{get;set;}
	}
	public class AddressResult
	{
		public AddressComponents[] address_components{get;set;}
		public string formatted_address{get;set;}
		public Geometry geometry{get;set;}
		public string[] types{get;set;}
	}
	public class GoogleLocationTest
	{
		public AddressResult[] results{get;set;}
		public string status{get;set;}
	}
	
	
    public class MakeBookingAsync : AsyncTask
    {
        private readonly Context _context;
        private readonly NewBooking _booking;
        private ProgressDialog p;
        private bool cantFindGps;

        public MakeBookingAsync(Context context, NewBooking booking)
        {
            _context = context;
            _booking = booking;
            cantFindGps = false;
        }

        protected override void OnPreExecute()
        {
            base.OnPreExecute();
            p = ProgressDialog.Show(_context,"Creating Booking...","Please Wait...",true,true);
            
        }


        protected override Object DoInBackground(params Object[] @params)
        {
            var api = new ApiService(Helper.GetServer(_context));
			     
			var result = api.ConvertAddressToGps(string.Format("{0}+{1}+{2},+{3},+ACT", _booking.StreetNumber,
                  _booking.Street, _booking.StreetType, _booking.Suburb, "ACT"));
				//Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(result);
				
				var t = Newtonsoft.Json.JsonConvert.DeserializeObject<GoogleLocationTest>(result).results.FirstOrDefault();
			
			
           /*   Geocoder g = new Geocoder(_context);
              var address = g.GetFromLocationName(string.Format("{0} {1} {2}, {3}, {4}", _booking.StreetNumber,
                  _booking.Street, _booking.StreetType, _booking.Suburb, "ACT"), 1).FirstOrDefault();*/
            if(t!= null && t.geometry != null && t.geometry.location != null )
            {
                _booking.Lat = t.geometry.location.lat;
                _booking.Lng = t.geometry.location.lng;
                return api.MakeBooking(_booking);
            }
            else
            {
                cantFindGps = true;
            }

            return -1;

        }

        protected override void OnPostExecute(Object result)
        {
            base.OnPostExecute(result);
            //hide and kill the progress dialog
            p.Hide();
            p.Cancel();

            if (cantFindGps)
            {
                Toast.MakeText(_context, "Sorry, We are unable to find your address.", ToastLength.Long);
            }
            else
            {


                //setup to show the confirmation screen
                Intent a = new Intent(_context, typeof (NewBookingProcessingActivity));
                a.AddFlags(ActivityFlags.ClearTop);

                //test deserialize and send booking id as reference number
                var res = Newtonsoft.Json.JsonConvert.DeserializeObject<Booking>(result.ToString());
                a.PutExtra("refNumber", res.BookingId.ToString());

                //store the serialized booking for later
                ISharedPreferencesEditor editor = PreferenceManager.GetDefaultSharedPreferences(_context).Edit();
                editor.PutString("lastBookingRef", result.ToString());
                editor.Commit();
                _context.StartActivity(a);
            }
        }
    }
	
	

    [Activity(Label = "Book Taxi")]
    public class BasicBookTaxiActivity : Activity
    {
       public static object getLocationInfo(String address) {

		/*HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?address=" + address + "ka&sensor=false");
		HttpClient client = new DefaultHttpClient();
		HttpResponse response;
		StringBuilder stringBuilder = new StringBuilder();

		try {
			response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			InputStream stream = entity.getContent();
			int b;
			while ((b = stream.read()) != -1) {
				stringBuilder.append((char) b);
			}
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}
			var res = Newtonsoft.Json.JsonConvert.DeserializeObject<Booking>(result.ToString());
		/*JSONObject jsonObject = new JSONObject();
		try {
			jsonObject = new JSONObject(stringBuilder.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/

		return 0;
	}
		
		public static GeoPoint getGeoPoint(object jsonObject) {
			
		/*Double lon = new Double(0);
		Double lat = new Double(0);

		try {

			lon = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
				.getJSONObject("geometry").getJSONObject("location")
				.getDouble("lng");

			lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
				.getJSONObject("geometry").getJSONObject("location")
				.getDouble("lat");

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/

		return new GeoPoint((int) (1 * 1E6), (int) (1 * 1E6));

	}
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.BookBasicTaxi);

            Button bookTaxiBtn = FindViewById<Button>(Resource.Id.bookNormalBtn);
            

            bookTaxiBtn.Click += (sender, e) =>
                                     {

                                         

                                         NewBooking booking = new NewBooking();
                                         booking.IMEI = Helper.GetDeviceId(ApplicationContext);
                                         booking.PhoneNumber = Helper.GetPhoneNumber(ApplicationContext);
                                         booking.NumberOfPassengers = 1;
                                         booking.Street = FindViewById<EditText>(Resource.Id.streetName_input).Text;
                                         booking.StreetNumber = FindViewById<EditText>(Resource.Id.street_input).Text != string.Empty ? Convert.ToInt32(FindViewById<EditText>(Resource.Id.street_input).Text) : 0;
                                         booking.StreetType = FindViewById<EditText>(Resource.Id.streetType_input).Text;
                                         booking.Suburb = FindViewById<EditText>(Resource.Id.suburb_input).Text;
                                         booking.UnitNumber = FindViewById<EditText>(Resource.Id.unit_input).Text != string.Empty ? 
                                             Convert.ToInt32(FindViewById<EditText>(Resource.Id.unit_input).Text) : 0;
				
				 
				
				//added api functionality to use webrequest to get around geocoder emulator issue.
				// un comment if using a 
			/*	var api = new ApiService();
				var result = api.ConvertAddressToGps(string.Format("{0}+{1}+{2},+{3},+ACT", booking.StreetNumber,
                  booking.Street, booking.StreetType, booking.Suburb, "ACT"));
				//Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(result);
				
				var t = Newtonsoft.Json.JsonConvert.DeserializeObject<GoogleLocationTest>(result);
				
                                          Geocoder g = new Geocoder(ApplicationContext);
              var address = g.GetFromLocationName(string.Format("{0}+{1}+{2},+{3},+ACT", booking.StreetNumber,
                  booking.Street, booking.StreetType, booking.Suburb, "ACT"), 1).FirstOrDefault();
				 */
                                         MakeBookingAsync asyncTask = new MakeBookingAsync(this, booking);
                                         
                                         asyncTask.Execute();
                                       
                                     };

            // Create your application here
        }

       
    }
}